<template>
  <el-container>
    <el-header>
      <el-form :inline="true" :model="queryForm">
        <el-form-item label="角色名称">
          <el-input v-model="queryForm.roleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button type="primary" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <el-table
        ref="roleTable"
        highlight-current-row
        @current-change="handleCurrentChange"
        max-height="500px"
        :data="roleData">
        <el-table-column prop="id" label="角色id"></el-table-column>
        <el-table-column prop="name" label="角色名称"></el-table-column>
        <el-table-column prop="nameZh" label="角色中文名称"></el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="sizes, prev, pager, next, jumper, ->, total, slot"
        :total="total">
      </el-pagination>
    </el-main>
    <el-footer>
      <el-row type="flex" justify="end">
        <el-button type="primary" @click="openAuthDialog">菜单授权</el-button>
        <el-button type="primary" @click="openDialog('addRole')">新增</el-button>
        <el-button type="primary" @click="openDialog('modifyRole')">修改</el-button>
        <el-popover placement="top" width="160px" v-model="visible" style="margin-left: 10px">
          <p>这个角色确定删除吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="delRole">确定</el-button>
          </div>
          <el-button slot="reference" type="primary">删除</el-button>
        </el-popover>
      </el-row>
    </el-footer>
    <OperationRoleDialog :dialog-visible="dialogFormVisible"
                         :form="roleForm"
                         :type="dialogOperation"
                         @query="query"
                         @close-dialog="closeDialog">
    </OperationRoleDialog>
    <el-dialog title="菜单授权" :visible.sync="authVisible" @close="closeAuthDialog" width="80%">
      <tree-transfer
        :title="title"
        :from_data='fromData'
        :to_data='toData'
        :defaultProps="{label:'label'}"
        :mode='mode'
        height='400px'
        filter
        openAll>
      </tree-transfer>
      <div style="text-align: right; margin: 10px">
        <el-button type="primary" @click="closeAuthDialog">取消</el-button>
        <el-button type="primary" @click="menuAuth">确定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
  import {postRequest} from "../../util/api";
  import {myMessage} from "../../util/myMessage";
  import OperationRoleDialog from "./dialog/OperationRoleDialog";
  import treeTransfer from 'el-tree-transfer';

  export default {
    name: "Role",
    components: {OperationRoleDialog, treeTransfer},
    data() {
      return {
        queryForm: {
          roleName: ''
        },
        roleData: [],
        pageSize: 5,
        currentPage: 1,
        total: 0,
        dialogFormVisible: false,
        dialogOperation: "addRole",
        roleForm: {
          id: 0,
          name: '',
          nameZh: ''
        },
        visible: false,
        authVisible: false,
        title: ["待选","已选"],    //标题 类型：Array 必填：false 默认：["源列表", "目标列表"]
        mode: "transfer", //设置模式，字段可选值为transfer|addressList 类型：String 必填：false 补充：mode默认为transfer模式，即树形穿梭框模式，可配置字段为addressList改为通讯录模式，通讯录模式时按钮不可自定义名字，如要自定义标题名在title数组传入四个值即可，addressList模式时标题默认为通讯录、收件人、抄送人、密送人
        fromData:[    //源数据 类型：Array 必填：true 补充：数据格式同element-ui tree组件，但必须有id和pid
          {
            id: "1",
            pid: 0,    //自定义pid的参数名，默认为"pid" 必填：false
            label: "一级 1",
            children: [
              {
                id: "1-1",
                pid: "1",
                label: "二级 1-1",
                disabled: true,
                children: []
              },
              {
                id: "1-2",
                pid: "1",
                label: "二级 1-2",
                children: [
                  {
                    id: "1-2-1",
                    pid: "1-2",
                    children: [],
                    label: "二级 1-2-1"
                  },
                  {
                    id: "1-2-2",
                    pid: "1-2",
                    children: [],
                    label: "二级 1-2-2"
                  }
                ]
              }
            ]
          },
        ],
        toData:[]
      }
    },
    created() {
      this.query();
    },
    methods: {
      getMenuTree() {
        postRequest('/system/menu/getMenuTree', {'role_id':this.roleForm.id}).then(res =>{
          if (res.status === 200) {
            this.fromData = [];
            this.toData = [];
            if (res.object.fromData !== null) {
              this.fromData.push(res.object.fromData);
            }
            if (res.object.toData !== null) {
              this.toData.push(res.object.toData);
            }
            console.log(res);
          } else {
            myMessage.error(res.message);
          }
        })
      },

      openAuthDialog() {
        this.closeAuthDialog();
        if (this.roleForm == null || this.roleForm.id === 0) {
          myMessage.warning("请选择一行要授权的角色！");
        } else {
          this.authVisible = true;
          this.getMenuTree();
        }
      },
      closeAuthDialog() {
          this.authVisible = false;
      },
      menuAuth() {
        this.closeAuthDialog();
        console.log(this.toData);
        postRequest('/system/role/menuAuthorization', {'role_id':this.roleForm.id, 'menus': this.toData}).then(res =>{
          if (res.status === 200) {
            this.query();
          } else {
            myMessage.error(res.message);
          }
        });
        this.reset();
      },
      resetQuery() {
        this.queryForm.roleName = '';
        this.pageSize = 5;
        this.currentPage = 1;
      },
      query() {
        let queryParam = JSON.parse(JSON.stringify(this.queryForm));
        queryParam.pageSize = this.pageSize;
        queryParam.currentPage = this.currentPage;
        postRequest('/system/role/getAllRoles', queryParam).then(res =>{
          if (res.status === 200) {
            this.roleData = res.object.data;
            this.total = res.object.total;
            if (this.total > 0 && this.roleData.length === 0) {
              this.resetQuery();
              this.query();
            }
          } else {
            myMessage.error(res.message);
          }
          this.queryForm.roleName = '';
        });
      },
      reset() {
        this.roleForm = {
          id: 0,
          name: '',
          nameZh: ''
        };
      },
      openDialog(value) {
        this.closeDialog();
        this.dialogOperation = value;
        if (value === 'modifyRole') {
          if (this.roleForm === null || this.roleForm.id === 0) {
            myMessage.warning("请选择一行数据");
          } else {
            this.dialogFormVisible = true;
          }
        } else {
          this.dialogFormVisible = true;
        }
      },
      closeDialog() {
        this.dialogFormVisible = false;
      },
      delRole() {
        this.visible = false;
        if (this.roleForm == null || this.roleForm.id === 0) {
          myMessage.warning("请选择要删除的数据");
        } else {
          postRequest('/system/role/deleteRole', {'role_id': this.roleForm.id}).then(resp=>{
            if (resp.status === 200) {
              this.query();
            }
          })
        }
        this.reset();
      },
      handleCurrentChange(val) {
        this.roleForm = JSON.parse(JSON.stringify(val));
      },
      sizeChange(size) {
        this.pageSize = size;
        this.query();
      },
      currentChange(page) {
        this.currentPage = page;
        this.query();
      }
    }
  }
</script>

<style scoped>

</style>
